package com.zhongfu.ai.web.buss;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongfu.ai.common.exceptions.BusinessException;
import com.zhongfu.ai.common.response.Result;
import com.zhongfu.ai.dto.AgentPageDto;
import com.zhongfu.ai.dto.AgentSaveDto;
import com.zhongfu.ai.entity.AiAgent;
import com.zhongfu.ai.service.IAiAgentService;
import com.zhongfu.ai.vo.AgentPageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * AI智能体主表 前端控制器
 * </p>
 *
 * @author tengyd
 * @since 2025-10-20
 */
@Slf4j
@RestController
@RequestMapping("/agent")
public class AiAgentController {

    @Autowired
    private IAiAgentService iAiAgentService;

    @PostMapping("/page")
    public Result agentList(@RequestBody AgentPageDto pageDto) {
        Page<AiAgent> page = iAiAgentService.page(new Page<>(pageDto.getPageNum(), pageDto.getPageSize()));
        return Result.success(page.convert(item -> BeanUtil.copyProperties(item, AgentPageVo.class)));
    }

    @PostMapping("/save")
    public Result agentSave(@RequestBody AgentSaveDto saveDto) {

        log.info("保存智能体：{}", saveDto);

        AiAgent aiAgent = new AiAgent();
        BeanUtils.copyProperties(saveDto, aiAgent);
        if (saveDto.getAgentId() == null) {
            aiAgent.setAgentId(IdUtil.getSnowflakeNextIdStr());
            iAiAgentService.save(aiAgent);
        } else {
            AiAgent existAgent = iAiAgentService.getOne(new LambdaQueryChainWrapper<>(AiAgent.class).getWrapper().eq(AiAgent::getAgentId, saveDto.getAgentId()));
            if (existAgent == null) {
                throw new BusinessException("智能体不存在");
            }
            BeanUtils.copyProperties(saveDto, existAgent);
            iAiAgentService.updateById(existAgent);
        }

        return Result.success("保存成功");
    }
}
